from coresales.utils import CurrencyField
from django.contrib.auth.models import User
from django.db import models
import datetime
from django.template import defaultfilters
import logging
import urllib
import os
from django.core.files import File
from decimal import Decimal
import math

logger = logging.getLogger(__name__)

STATE_CHOICES = (
        ('SALED', 'Saled'),
        ('WAIT_TO_SALE', 'Wait to Sale'),
)
    
class Client(models.Model):
    user = models.ForeignKey(User)
    documentNumber =  models.CharField(max_length=20)
    address = models.CharField(max_length=200)
    telephoneNumber = models.CharField(max_length=12)
    celularNumber   = models.CharField(max_length=12)
    creationDate = models.DateField(default=datetime.datetime.now)
    def __str__(self):
        return self.user.__str__()

class Catalog(models.Model):
    name = models.CharField(max_length=50,unique=True)
    displayToolTip= models.CharField(max_length=50)
    slug = models.SlugField(max_length=200,unique=True,blank=True)
    def __str__(self):
        return self.name.__str__() 
    
    def save(self, force_insert=False, force_update=False,*args, **kwargs):
        if not self.id:
            self.slug = defaultfilters.slugify(self.name)
            super(Catalog, self).save(force_insert, force_update)
            logger.info("Saved Catalog")
        try:
            #ping_google()
            logger.info("Ping search engines")
        except Exception:
            logger.error("Some error happens when Pinging search engines.")
            pass
class Category(models.Model):
    name = models.CharField(max_length=50,unique=True)
    catalog= models.ForeignKey(Catalog)
    slug = models.SlugField(max_length=200,unique=True,blank=True)
    def save(self, force_insert=False, force_update=False,*args, **kwargs):
        if not self.id:
            self.slug = defaultfilters.slugify(self.name)
            super(Category, self).save(force_insert, force_update)
            logger.info("Ping search engines")
        try:
            #ping_google()
            logger.info("Ping search engines")
        except Exception:
            logger.error("Some error happens when Pinging search engines.")
            pass
    def __str__(self):
        return self.name.__str__() + '-' + self.catalog.__str__()
     
class Photo(models.Model):
    relativePath=models.CharField(max_length=200)
    title   = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to=relativePath)
    def reload(self):
        """Store image locally if we have a URL"""
        if self.url and not self.photo:
            result = urllib.urlretrieve(self.url)
            self.photo.save(
                    os.path.basename(self.url),
                    File(open(result[0], 'rb'))
                    )
            self.save()
    def __str__(self):
        return str(self.id) +  '-' + self.title.__str__() 
 
class Product(models.Model):
    code = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)
    description   = models.CharField(max_length=400)
    category=models.ForeignKey(Category, related_name='products')
    costPrice = CurrencyField(max_digits=10, decimal_places=2)
    price = CurrencyField(max_digits=10, decimal_places=2)
    photo  = models.ForeignKey(Photo)
    slug = models.SlugField(max_length=200,unique=True,blank=True)
    public = models.BooleanField()
    lastPublication= models.BooleanField()
    countOfVisitors=models.IntegerField()
     
    def clickToDetail(self):
        self.countOfVisitors=self.countOfVisitors+1
        self.save()     
                                  
    def save(self, force_insert=False, force_update=False,*args, **kwargs):
        self.slug = defaultfilters.slugify(self.name)
        self.price=math.ceil(Decimal(self.costPrice* Decimal(1.21)))
        super(Product, self).save(force_insert, force_update)
        try:
            #ping_google()
            logger.info("Ping search engines")
        except Exception:
            logger.error("Some error happens when Pinging search engines.")
            pass
    def __str__(self):
        return self.code.__str__() + '-' + self.category.__str__()

class PriceIncrement(models.Model):
    rate =  models.DecimalField(max_digits=10, decimal_places=2)
    creationDate = models.DateField(default=datetime.datetime.now)
    def save(self, force_insert=False, force_update=False,*args, **kwargs):
        for product in Product.objects.all():
            product.costPrice = product.costPrice * self.rate
            product.save()
            super(PriceIncrement, self).save(force_insert, force_update)
        
class ProductAttribute(models.Model):
        name = models.CharField(max_length=300)
        description = models.TextField(blank=True)
        def __unicode__(self):
            return u'%s' % self.name   
    
class ProductDetail(models.Model):
    product=models.ForeignKey(Product)
    attribute = models.ForeignKey(ProductAttribute)
    value = models.CharField(max_length=500)
    description = models.TextField(blank=True)
    def save(self, force_insert=False, force_update=False,*args, **kwargs):
        super(ProductDetail, self).save(force_insert, force_update)
        try:
            #ping_google()
            logger.info("Ping search engines")
        except Exception:
            logger.error("Some error happens when Pinging search engines.")
            pass
    def __unicode__(self):
        return u'%s: %s - %s' % (self.product,
                                 self.attribute,
                                 self.value)

class Cart(models.Model):
    code = models.AutoField(primary_key=True)
    sessionId= models.CharField(max_length=255)
    user=  models.ForeignKey(User,null=True)
    state = models.CharField(max_length=15, choices=STATE_CHOICES)
    creationDate = models.DateField(default=datetime.datetime.now)
    def __str__(self):
        return str(self.code) + '-' + self.sessionId.__str__() + '-' + self.user.__str__()
class OrderProduct(models.Model):
    id = models.AutoField(primary_key=True)
    product =  models.ForeignKey(Product)
    unitPrice = CurrencyField(max_digits=10, decimal_places=2, blank=True)
    subTotalPrice = CurrencyField(max_digits=10, decimal_places=2, blank=True)
    quantity = models.IntegerField()
    cart = models.ForeignKey(Cart)
    def __str__(self):
        return str(self.id) + '-' + self.product.__str__()
class Order(models.Model):
    code = models.AutoField(primary_key=True)
    cart = models.ForeignKey(Cart)
    registrationDate = models.DateField(default=datetime.datetime.now)
    def __str__(self):
        return str(self.code) + '-' + str(self.cart.code)
